package handle

import (
	"errors"
	"fmt"
	"net/url"
	"regexp"
	"strings"
)

//https://mvnrepository.com/artifact/software.amazon.awssdk/auth
////implementation("software.amazon.awssdk:auth:2.32.20")

type Imp string
type Key string

func (k Key) Key() string {
	split := strings.Split(string(k), "-")
	for i, s := range split {
		if i == 0 {
			continue
		}
		if len(s) == 0 {
			continue
		}
		split[i] = strings.ToUpper(s[:1]) + s[1:]
	}
	return strings.Join(split, "")
}

var depRegexp = regexp.MustCompile(`^(\w+)\("([^:]+):([^:]+):([^"]+)"\)$`)

func (i Imp) ToDep() (Dep, error) {
	submatch := depRegexp.FindStringSubmatch(string(i))
	if len(submatch) != 5 {
		return Dep{}, errors.New("invalid dependency format")
	}

	return Dep{
		Method:     submatch[1],
		GroupId:    submatch[2],
		ArtifactId: submatch[3],
		Version:    submatch[4],
		Scope:      "",
	}, nil
}

type Dep struct {
	Method     string `json:"method" toml:"method"`
	GroupId    string `json:"groupId" toml:"groupId"`
	ArtifactId string `json:"artifactId" toml:"artifactId"`
	Version    string `json:"version" toml:"version"`
	Scope      string `json:"scope" toml:"scope"`
}

func (dep Dep) Key(handle func(str string) string) Key {
	prefix := strings.TrimRight(dep.GroupId, dep.ArtifactId) + "." + dep.ArtifactId
	all := strings.ReplaceAll(prefix, ".", "-")
	if handle != nil {
		all = handle(all)
	}
	return Key(all)
}

func (dep Dep) ToRaw(version string) string {
	//return fmt.Sprintf(`%s:%s")`,
	//	dep.GroupId,
	//	dep.ArtifactId,
	//)
	return fmt.Sprintf(`%s("%s:%s:%s")`,
		dep.Method,
		dep.GroupId,
		dep.ArtifactId,
		version,
	)
}

func (dep Dep) ToLib() (Key, Library) {
	return dep.Key(nil), Library{
		Module:     dep.GroupId + ":" + dep.ArtifactId,
		VersionRef: dep.Version,
	}
}

func (dep Dep) ToPlugin() (Key, Plugin) {
	key := dep.Key(func(str string) string {
		return strings.TrimRight(str, "gradle-plugin")
	})
	return key, Plugin{
		Id:         dep.GroupId + ":" + dep.ArtifactId,
		VersionRef: dep.Version,
	}
}

func (dep Dep) IsPlugin() bool {
	return strings.Contains(dep.ArtifactId, "gradle-plugin")
}

const basicUrl = "https://mvnrepository.com/"

func (dep Dep) URL() (string, error) {
	return url.JoinPath(basicUrl, "artifact", dep.GroupId, dep.ArtifactId)
}
